﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.AspNetCore.Mvc.Extensions;
using Abp.UI;
using FwProject.Authorization.Users;
using FwProject.Car;
using FwProject.Controllers;
using FwProject.Core.Restaurant;
using FwProject.Distribution;
using FwProject.Distribution.Dto;
using FwProject.Distribution.Dto.Statistics;
using FwProject.Restaurant;
using FwProject.Restaurant.Dto;
using FwProject.TypeNumber;
using FwProject.Users;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using X.PagedList;

namespace FwProject.Web.Mvc.Controllers
{
    [AbpMvcAuthorize]
    public class DistributionController : FwProjectControllerBase
    {
        private readonly ICarInfoAppService _carInfoAppService;
        private readonly ILoadCarAppService _loadCarAppService;
        private readonly ILoadingCarAppService _loadingCarAppService;
        private readonly IDistributionAppService _distributionAppService;
        private readonly IDistributionDetailsAppService _distributionDetailsAppService;
        private readonly IUserAppService _userAppService;
        private readonly ITypeNumberInfoAppService _typeNumberInfoAppService;
        private readonly IRestaurantTypeNumberAppService _restaurantTypeNumberAppService;
        private readonly IRestaurantAppService _restaurantAppService;
        private readonly IDistributionHistoryAppService _distributionHistoryAppService;
        private readonly IHostingEnvironment _env;


        public DistributionController(ICarInfoAppService carInfoAppService, ILoadCarAppService loadCarAppService,
            ILoadingCarAppService loadingCarAppService, IDistributionAppService distributionAppService, IDistributionDetailsAppService distributionDetailsAppService, IRestaurantAppService restaurantAppService,
            IHostingEnvironment env, IUserAppService userAppService, ITypeNumberInfoAppService typeNumberInfoAppService, IRestaurantTypeNumberAppService restaurantTypeNumberAppService, IDistributionHistoryAppService distributionHistoryAppService)
        {
            _carInfoAppService = carInfoAppService;
            _loadCarAppService = loadCarAppService;
            _loadingCarAppService = loadingCarAppService;
            _distributionAppService = distributionAppService;
            _distributionDetailsAppService = distributionDetailsAppService;
            _env = env;
            _userAppService = userAppService;
            _typeNumberInfoAppService = typeNumberInfoAppService;
            _restaurantTypeNumberAppService = restaurantTypeNumberAppService;
            _restaurantAppService = restaurantAppService;
            _distributionHistoryAppService = distributionHistoryAppService;
        }

        #region 装车
        /// <summary>
        /// 装车单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<IActionResult> LoadingInvoice(int? id, int size, LoadInvoiceFilter filter = null)
        {
            int pageNumber = id ?? 1;
            if (size == 0)
                size = 20;

            if (Request.IsAjaxRequest())
            {
                var data = await _loadCarAppService.GetAllLoadingInvoiceAsync(pageNumber, size, filter);
                return PartialView("LoadingInvoicePartial", data);
            }


            return View();
        }
        /// <summary>
        /// 装车录入
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> CreateLoadCar()
        {
            var usermodel = await _userAppService.GetByIdUserAsync(AbpSession.UserId.Value);
            var model = await _userAppService.GetAllByTypeAsync(EmployeeType.司机类型, null, "");
            ViewBag.Driver = model.Where(o => o.FactoryInfoId == usermodel.FactoryinfoId);
            var typenumber = await _typeNumberInfoAppService.GetAllTypeNumber();
            ViewBag.TypeNumber = typenumber;
            return View();
        }

        [HttpPost]
        public async Task<JsonResult> CreateLoadCar(long DriverId, LoadCarInputDto input)
        {

            var car = await _carInfoAppService.GetByIdAsync(DriverId);
            if (car == null)
                throw new UserFriendlyException(200, "该司机没有绑定车辆！");
            input.Carinfoid = car.Id;
            input.DriverUserId = DriverId;
            input.LoadingCarInputs = input.LoadingCarInputs.Where(o => o.Countproduct > 0).ToList();

            if (input.LoadingCarInputs == null || input.LoadingCarInputs.Count == 0)
                throw new UserFriendlyException(200, "型号数量有误，请重新输入！");

            var id = await _loadCarAppService.Create(input);
            return Json(id);

            //return Redirect("/Distribution/ExamineLoadingCar?id="+id);
        }
        /// <summary>
        /// 装车单审核
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ExamineLoadingCar(Guid id)
        {
            //var typenumber = await _typeNumberInfoAppService.GetAllTypeNumber();
            //ViewBag.TypeNumber = typenumber;
            var model = await _loadCarAppService.GetLoadingInvoiceAsync(id);
            var data = await _loadingCarAppService.GetAllListByloadId(id);
            Tuple<LoadCarOutputDto, List<LoadingCarDto>> tuple = new Tuple<LoadCarOutputDto, List<LoadingCarDto>>(model, data);
            return View(tuple);
        }

        public async Task<IActionResult> EditStatus(Guid id, ExamineStatus examine)
        {
            await _loadCarAppService.UpdateStatus(id, examine);

            return Json("success");
        }

        public async Task<IActionResult> UpdateTypeNumber(Guid id)
        {
            var typenumber = await _loadCarAppService.GetLoadCarInfo(id);
            ViewBag.Id = id;
            return View(typenumber);
        }
        [HttpPost]
        public async Task<JsonResult> UpdateTypeNumber(Guid id, LoadCarTypesEnterDto input)
        {
            await _loadCarAppService.UpdateType(id, input);
            return Json(id);
        }
        /// <summary>
        /// 装车单导出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ExportLoadingInvoice(LoadInvoiceFilter filter = null)
        {
            var list = await _loadCarAppService.GetLoadingInvoiceListAsync(filter);
            return DoExcel<LoadCarExportDto>(list, _env);

        }
        /// <summary>
        /// 装车明细
        /// </summary>
        /// <param name="id"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<IActionResult> LoadingDetails(int? id, int size, LoadDetailsFilter filter = null)
        {
            int pageNumber = id ?? 1;

            if (size == 0)
                size = 10;

            if (Request.IsAjaxRequest())
            {
                var data = await _loadCarAppService.GetLoadDetailsAsync(pageNumber, size, filter);
                return PartialView("LoadingDetailsPartial", data);
            }
            return View();
        }

        /// <summary>
        /// 装车数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<JsonResult> GetLoadingCarData(Guid id)
        {
            var data = await _loadingCarAppService.GetAllListByloadId(id);
            return Json(data);
        }
        #endregion

        #region 配送
        /// <summary>
        /// 配送列表
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<IActionResult> DistributionIndex(int pageIdx, int size, DateTime? beginTime, DateTime? endTime)
        {
            if (pageIdx == 0)
                pageIdx = 1;
            size = size == 0 ? 20 : size;
            var model = await _distributionAppService.GetPagedListAsync(pageIdx, size, beginTime, endTime);
            if (Request.IsAjaxRequest())
            {
                return PartialView("DistributionPartial", model);
            }
            return View(model);
        }
        /// <summary>
        /// 配送列表导出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ExportDistributionList()
        {
            var list = await _distributionAppService.GetExportDistributionListAsync();
            return DoExcel<DistributionViewDto>(list, _env);

        }

        /// <summary>
        /// 配送单
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="RestaurantName"></param>
        /// <param name="PlatesNumber"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<ActionResult> DistributionDetails(int pageIdx, int size, string RestaurantName, string DriverName, DateTime? beginTime, DateTime? endTime, string key)
        {
            if (pageIdx == 0)
                pageIdx = 1;
            if (size == 0)
                size = 20;
            var list = _distributionAppService.GetDetailsCount(RestaurantName, DriverName, beginTime, endTime);
            ViewBag.Distributioncount = list.Sum(o => o.Distributioncount);
            ViewBag.DistributionBycount = list.Sum(o => o.DistributionBycount);
            ViewBag.Recoverycount = list.Sum(o => o.Recoverycount);
            ViewBag.RecoveryBycount = list.Sum(o => o.RecoveryBycount);
            ViewBag.Exchangegoodscount = list.Sum(o => o.Exchangegoodscount);
            ViewBag.ExchangegoodsBycount = list.Sum(o => o.ExchangegoodsBycount);
            ViewBag.Damagecount = list.Sum(o => o.Damagecount);
            ViewBag.Givecount = list.Sum(o => o.Givecount);
            ViewBag.GiveBycount = list.Sum(o => o.GiveBycount);
            ViewBag.Backboxcount = list.Sum(o => o.Backboxcount);
            ViewBag.Backnumbercount = list.Sum(o => o.Backnumbercount);
            ViewBag.BackboxSumBycount = list.Sum(o=>o.BackboxSumBycount);
            ViewBag.TotalPrice = list.Sum(o => o.TotalPrice);

            var typenumber = await _distributionAppService.GetRestaurantTypeNumberListAsync(pageIdx, size);
            //if (key == "1")
            //{
            if (Request.IsAjaxRequest())
            {
                var model = await _distributionAppService.GetDetailsPagedListAsync(pageIdx, size, RestaurantName, DriverName, beginTime, endTime);
                return PartialView("DistributionDetailsPartial", model);
            }
            return View();
            //}
            //else
            //{
            //    if (Request.IsAjaxRequest())
            //    {
            //        return PartialView("RestaurantTypeNumberPartial", typenumber);
            //    }
            //    return View(typenumber);
            //}

        }
        /// <summary>
        /// 查看历史记录
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> History(Guid id, int pageIdx, long? AgentPeoperUserId, DateTime? beginTime, DateTime? endTime)
        {
            ViewBag.Id = id;
            if (pageIdx == 0)
                pageIdx = 1;
            var model = await _distributionHistoryAppService.GetPagedListAsync(id, pageIdx, 20, AgentPeoperUserId, beginTime, endTime);
            if (Request.IsAjaxRequest())
            {
                return PartialView("HistoryPartial", model);
            }
            return View(model);
        }

        /// <summary>
        /// 修改型号单价
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> EditTypeNumberPrice(Guid id)
        {
            var model = await _restaurantTypeNumberAppService.GetByIdAsync(id);
            return View(model);
        }
        [HttpPost]
        public async Task<JsonResult> EditTypeNumberPrice(Guid id, decimal Price)
        {
            await _restaurantTypeNumberAppService.EditPrice(id, Price);
            return Json(id);
        }
        /// <summary>
        /// 重计金额
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> RecalculatePrice(Guid id)
        {
            await _distributionAppService.RecalculatePrice(id);
            return Redirect("/Distribution/DetailsInformation?id=" + id);
        }

        public async Task<IActionResult> EditDistributionDeltails(Guid id, DistributionInpuDto input, long CreatorUserId)
        {
            await _distributionAppService.EditDistribution(id, input, CreatorUserId);

            return Json(id);
        }

        /// <summary>
        /// 配送明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<JsonResult> GetDistrbutionData(Guid id)
        {
            var data = await _distributionDetailsAppService.GetByIdDistributionDetailsListAsync(id);
            return Json(data);
        }
        /// <summary>
        /// 配送单导出
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="RestaurantName"></param>
        /// <param name="DriverName"></param>
        /// <returns></returns>
        public async Task<IActionResult> ExportDistributionDetails(DateTime? beginTime, DateTime? endTime, string RestaurantName, string DriverName)
        {
            var list = await _distributionAppService.GetDetailsListAsync(RestaurantName, DriverName, beginTime, endTime);
            return DoExcel<DistributionDetailsListViewDto>(list, _env);

        }
        /// <summary>
        /// 配送详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> DetailsInformation(Guid id)
        {

            var model1 = _distributionAppService.GetDetailsById(id);
            var model2 = await _distributionDetailsAppService.GetDistributionByIdAsync(id);
            Tuple<DistributionDetailsView, List<DistributionDetailsDto>> tuple = new Tuple<DistributionDetailsView, List<DistributionDetailsDto>>(model1, model2);

            return View(tuple);
        }

        /// <summary>
        /// 配送详情打印页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Print(Guid id)
        {
            var model1 = _distributionAppService.GetDetailsById(id);
            var model2 = await _distributionDetailsAppService.GetDistributionByIdAsync(id);
            Tuple<DistributionDetailsView, List<DistributionDetailsDto>> tuple = new Tuple<DistributionDetailsView, List<DistributionDetailsDto>>(model1, model2);
            var user = await UserManager.FindByIdAsync(model1.CreatorUserId.ToString());
            ViewBag.UserName = user.Name;
            return View(tuple);
        }

        /// <summary>
        /// 配送签收
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> SignIndex(int pageIdx, string RestaurantName, string Pricestatus, string DriverName, DateTime? beginTime, DateTime? endTime)
        {
            if (pageIdx == 0)
                pageIdx = 1;


            if (Request.IsAjaxRequest())
            {
                var model = await _distributionAppService.GetSignPagedListAsync(pageIdx, 20, RestaurantName, Pricestatus, DriverName, beginTime, endTime);
                return PartialView("SignIndexPartial", model);
            }
            return View();
        }
        /// <summary>
        /// 配送签收导出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ExportDistributionSign(string RestaurantName, string Pricestatus, string DriverName, DateTime? beginTime, DateTime? endTime)
        {
            var list = await _distributionAppService.GetExportSignListAsync(RestaurantName, Pricestatus, DriverName, beginTime, endTime);
            return DoExcel<DistributionDetailsView>(list, _env);
        }

        public async Task<JsonResult> GetRestaurantData(long driverId)
        {
            var restaurant = await _restaurantAppService.GetRestaurantByDriverIdAsync(driverId);
            return Json(restaurant);
        }

        public async Task<IActionResult> AddDistribution()
        {
            var driver = await _userAppService.GetAllByTypeAsync(EmployeeType.司机类型, null, "");
            ViewBag.Driver = driver;
            return View();
        }

        [HttpPost]
        public async Task<JsonResult> AddDistribution(DistributionInpuDto input, long DriverId, int ActualCount)
        {
            //var stock = ActualCount + input.DetailsInputDtos.Sum(o => o.Distributioncount) + input.DetailsInputDtos.Sum(o => o.Givecount) - input.DetailsInputDtos.Sum(o => o.Recoverycount);
            //await _restaurantAppService.EditStock(input.Restaurantid, ActualCount);
            List<DistributionDetailsInputDto> list = new List<DistributionDetailsInputDto>();
            foreach (var item in input.DetailsInputDtos)
            {
                if (item.Backboxcount == 0 && item.Backnumbercount == 0 && item.Damagecount == 0 && item.Distributioncount == 0 && item.Exchangegoodscount == 0 && item.Givecount == 0 && item.Recoverycount == 0)
                    list.Add(item);
            }
            foreach (var item in list)
            {
                input.DetailsInputDtos.Remove(item);
            }

            await _loadCarAppService.CreateLoadCarAndDistribution(input, DriverId);

            return Json(1);
        }

        #endregion

        #region 车辆监控
        /// <summary>
        /// 配送轨迹
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Track()
        {
            var data = await _carInfoAppService.GetCarTrackAsync("");
            return View(data);
        }
        /// <summary>
        /// 配送轨迹（数据）
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<JsonResult> TrackData(string keyword = "")
        {
            var data = await _carInfoAppService.GetCarTrackAsync(keyword);
            return Json(data);
        }
        #endregion
    }
}